/* 
* Javascript code for forms on the Create new Group page from groups/create.php
*
*/


/* **********************************************************
 *	Functions for the email list text area. Purpose is to detect when an email
 *  is typed,  append it to the screen and create a hidden input for the server
 *	to parse.
*************************************************************/
var textarea = document.getElementById("email-list");
var endOfEmailIndex = 0;
var counter = 0;
var textWasPasted = false;
var arrayOfEmails;
				
//This keyup function detects if a ';' is the was released
//If it is, then it uses the lastly typed string to call appendToScreen(), addHiddenInput(), and incrementEmailCount()
textarea.addEventListener("keyup", function(e) {

	// Only execute the following code if the text was not pasted
	if( textWasPasted == false) {
		var inputString = textarea.value;
		if( e.keyCode == 186 ){ //Keycode for semi-colon
			var stringIndex = inputString.lastIndexOf(';');
			if( endOfEmailIndex == 0 )
				var email = inputString.substring(endOfEmailIndex, stringIndex);
			else
				var email = inputString.substring(endOfEmailIndex+1, stringIndex);
			
			endOfEmailIndex = stringIndex;
			appendToScreen(email);		
			addHiddenInput(email);
			incrementEmailCount();
		}
	} else
		textWasPasted = false;  //Reset the boolean variable	
}, false);
				
detectPaste(textarea, function(pastedText) {
	textWasPasted = true;
	// Assuming the pasted text has multiple emails in it, split the text into an array separated by ';'
	var emailArray = (pastedText.text).split(';');
	for( var i=0; i<emailArray.length-1; ++i) {
		appendToScreen(emailArray[i]);
		addHiddenInput(emailArray[i]);
		incrementEmailCount();
	}
	endOfEmailIndex += pastedText.length + 1; //Move the end of email index to the end of the pasted text

});

function appendToScreen(email){
	//Find the <div> #email-output, create a new <p> element, create a TextNode to append to the paragraph and
	// append the paragraph to the <div>. This function must appear before addHiddenInput() because of the counter
	var output = document.getElementById("email-output");
	var newPara = document.createElement('p');
	var newText = document.createTextNode(email);
	newPara.id = 'email-output'+counter;
	newPara.appendChild(newText);
	output.appendChild(newPara);
}
	
function addHiddenInput( email ) {
	// Create a new input field with value of the passed in email address and append it to the end of the form
	var newInput = document.createElement('input');
	newInput.type = 'hidden';
	newInput.id = 'email-address'+counter;
	newInput.value = email;
	document.forms['create-group-form'].appendChild(newInput);
	++counter;
}

function incrementEmailCount(){
	//Must appear after addHiddenInput() because of the counter
	var para = document.getElementById("email-output-count");
	para.innerHTML = "Email addresses detected: "+counter;
}
				
function getTextAreaSelection(textarea) {
	//Find the area of the passed in textarea field
    var start = textarea.selectionStart, end = textarea.selectionEnd;
    return {
        start: start,
        end: end,
        length: end - start,
        text: textarea.value.slice(start, end)
    };
}

function detectPaste(textarea, callback) {
    textarea.onpaste = function() {
		var sel = getTextAreaSelection(textarea);
		var initialLength = textarea.value.length;
		window.setTimeout(function() {
			var val = textarea.value;
			var pastedTextLength = val.length - (initialLength - sel.length);
			var end = sel.start + pastedTextLength;
			callback({
				start: sel.start,  
				end: end,
				length: pastedTextLength,
				text: val.slice(sel.start, end)  //String containing the value of the pasted text
			});
		}, 1);
    };
}

function add_email_textbox(){
	var input = document.getElementById("add-email-textbox");
	email = input.value;
	appendToScreen(email);
	addHiddenInput( email );
	incrementEmailCount();
	input.value = '';
}			
				

/* **********************************************************
 *	Functions to dynamically add and remove text boxes
*************************************************************/
function add_another_email_textbox() {
	// Function called from #add-button in groups/create.php
	var num     = $('.email-textbox').length; // how many "duplicatable" input fields we currently have
	var newNum  = new Number(num + 1);      // the numeric ID of the new input field being added

	// create the new element via clone(), and manipulate it's ID using newNum value
	var newElem = $('#input' + num).clone().attr('id', 'input' + newNum).attr('value', '');

	// manipulate the name/id values of the input inside the new element
	newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);

	// insert the new element after the last "duplicatable" input field
	$('#input' + num).after(newElem);
	
	// business rule: you can only add 20 emails
	// Once the button is disabled, theres no way to re-enable it
	if (newNum == 20) {
		alert("You can only add up to 20 email addresses during registration. If you need to add more members, you can do so after your Group is created by clicking the 'Admin' tab when viewing your Group.");
		$('#add-another-button').attr('disabled','disabled');
	}
}

function remove_email_textbox(){

	var num = $('.email-textbox').length; // how many "duplicatable" input fields we currently have
	if (num != 1)
		$('#input' + num).remove();     // remove the last element

	// enable the "add" button
	//$('#add-button').attr('disabled','');

	// if only one element remains, disable the "remove" button
	//if (num-1 == 1)
		//$('#remove-button').attr('disabled','disabled');
}